<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 工具条 -->
      <pageTools :title="`共计${total}条`">
        <el-button
          type="danger"
          size="small"
          @click="exportFile"
        >普通excel导出</el-button>
        <el-button
          type="info"
          size="small"
          @click="exportFile2"
        >复杂表头excal导出</el-button>
        <el-button
          type="success"
          size="small"
          @click="$router.push('/import?type=user')"
        >Excel导入</el-button>
        <el-button
          type="primary"
          size="small"
          @click="showDialog = true"
        >新增员工</el-button>
      </pageTools>
      <!-- 表格 -->
      <el-table :data="list" border="">
        <el-table-column type="index" label="序号" />
        <el-table-column prop="username" label="姓名" />
        <el-table-column label="工号" sortable="" prop="workNumber" />
        <!-- <el-table-column label="聘用形式" prop="formOfEmployment" /> -->
        <!-- <template slot-scope="scope"> -->
        <!-- {{scope.row}} -->
        <!-- <span v-if="scope.row.formOfEmployment*1===1">正式</span>
          <span v-if="scope.row.formOfEmployment*1===2">非正式</span> -->
        <!-- </template> -->
        <el-table-column
          label="聘用形式"
          :formatter="formatterFn"
          prop="formOfEmployment"
        />
        <el-table-column label="部门" sortable="" prop="departmentName" />
        <el-table-column label="入职时间" sortable="" prop="timeOfEntry" />
        <el-table-column label="账户状态" sortable="" prop="enableState" />
        <el-table-column label="操作" sortable="" fixed="right" width="280">
          <template slot-scope="{ row }">
            <el-button type="text" @click="$router.push('/employees/details/'+ row.id)">查看</el-button>
            <el-button type="text">转正</el-button>
            <el-button type="text">调岗</el-button>
            <el-button type="text">离职</el-button>
            <el-button type="text" @click="editRole(row.id)">角色</el-button>
            <el-button type="text" @click="delHandler(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 弹窗 -->
      <el-dialog
        title="新增员工"
        :visible.sync="showDialog"
        width="50%"
        @click="cancel"
      >
        <el-form
          ref="form"
          :model="formData"
          :rules="formRules"
          label-width="180px"
        >
          <el-form-item label="姓名" prop="username">
            <el-input v-model="formData.username" />
          </el-form-item>
          <el-form-item label="头像" prop="username">
            <el-input v-model="formData.username" />
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="formData.mobile" />
          </el-form-item>
          <el-form-item label="入职时间" prop="timeOfEntry">
            <el-date-picker
              v-model="formData.timeOfEntry"
              type="datetime"
              placeholder="选择日期"
            />
          </el-form-item>
          <el-form-item label="聘用形式" prop="formOfEmployment">
            <el-select v-model="formData.formOfEmployment" style="width: 240px">
              <el-option
                v-for="item in hireType"
                :key="item.id"
                :label="item.value"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="工号" prop="workNumber">
            <el-input v-model="formData.workNumber" />
          </el-form-item>
          <el-form-item label="部门" prop="departmentName">
            <el-input v-model="formData.departmentName" />
            <el-cascader
              v-model="formData.departmentName"
              :options="departs"
              :props="{ label: 'name', value: 'name' }"
            />
          </el-form-item>
          <el-form-item label="转正时间">
            <el-date-picker
              v-model="formData.correctionTime"
              type="datetime"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="showDialog = false">cancel</el-button>
          <el-button type="primary" @click="btnOK">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 放置角色分配组件 -->
      <assign-role ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { formatDate } from '@/filters'
import employeesConstant from '@/api/constant/employees'
import {
  getEmployeeListData,
  delEmployeeData,
  addEmployeeInfo
} from '@/api/employees'
import { tranListToTreeData } from '@/utils/index'
import { getDepartmentListData } from '@/api/department'
// import pageTools from '@/components/pageTools'
import AssignRole from './components/assign-role.vue' // 导入组件
export default {
  components: {
    AssignRole // 注册组件
  },
  data() {
    return {
      showDialog: false,
      formData: {},
      formRules: {
        username: [{ required: true, message: '请输入', trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入', trigger: 'blur' }],
        formOfEmployment: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        timeOfEntry: [{ required: true, message: '请输入', trigger: 'blur' }],
        workNumber: [{ required: true, message: '请输入', trigger: 'blur' }],
        departmentName: [
          { required: true, type: 'array', message: '请输入', trigger: 'blur' }
        ]
      },
      // 列表数据
      list: [],
      // 查询参数
      queryData: {
        page: 1,
        size: 10
      },
      // 总数
      total: 0,
      hireType: employeesConstant.hireType,
      departs: [],

      userId: null, // 用户id
      showRoleDialog: false
    }
  },
  created() {
    this.initData()
    this.getDepertsData()
  },
  methods: {
    async initData() {
      const { rows, total } = await getEmployeeListData(this.queryData)
      this.total = total
      this.list = rows
    },
    // 列格式化函数
    formatterFn(row, colum, cellVallue, index) {
      const res = this.hireType.find((item) => item.id === cellVallue * 1)
      return res ? res.value : '未知'
    },
    // 删除
    async delHandler(id) {
      await this.$confirm('确认删除吗？')
      await delEmployeeData(id)
      this.$message.success('删除成功')
      if (this.queryData.page !== 1 && this.list.length === 1) {
        this.queryData.page--
      }
      this.initData()
    },
    // 获取部门列表
    async getDepertsData() {
      const { depts } = await getDepartmentListData(this.queryData)
      this.departs = tranListToTreeData(depts, '')
    },
    // 提交表单
    async btnOK() {
      await this.$refs.form.validate()
      // 加工（拷贝）数据  发送请求
      const departmentName = this.formData.departmentName
      await addEmployeeInfo({
        ...this.formData,
        departmentName: departmentName[departmentName.length - 1]
      })
      this.$message.success('增加成功')
      this.showDialog = false
      this.initData()
    },
    // 取消
    cancel() {
      this.formData = {}
      this.$refs.form.clearValidate()
    },
    // 普通导出
    exportFile() {
      // import xx from 'xx' 表示导入，只要写webpack就会识别打包
      // 如何动态加载模块  import（'路径'） 返回Promise
      import('@/vendor/Export2Excel').then(async(excel) => {
        // console.log(excel) // 是整个导入的模块
        // 1.请求呀导出的数据
        const { headerData, bodyData } = await this.getData()
        // 3.调用插件的导出方法
        excel.export_json_to_excel({
          header: headerData, // 表头
          data: bodyData, // 表格数据
          filename: '员工信息' // 文件名称
        })
      })
    },
    // 复杂数据导出
    exportFile2() {
      import('@/vendor/Export2Excel').then(async(excel) => {
        const { headerData, bodyData } = await this.getData()
        // 3.调用插件的导出方法
        excel.export_json_to_excel({
          multiHeader: [['姓名', '基本信息', '', '', '', '', '部门']],
          merges: ['A1:A2', 'B1:F1', 'G1:G2'],
          header: headerData, // 表头
          data: bodyData, // 表格数据
          filename: '员工信息2' // 文件名称
        })
      })
    },
    async getData() {
      const { rows } = await getEmployeeListData({ page: 1, size: 10000 })
      const headers = {
        手机号: 'mobile',
        姓名: 'username',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      const headerData = Object.keys(headers)
      const bodyData = rows.map((item) => {
        // item是每个数据对象
        // headerData 是表头
        const res = headerData.map((key) => {
          // key是每个中文， headers[key]是每个中文对应的英文
          if (['timeOfEntry', 'correctionTime'].includes(headers[key])) {
            return formatDate(item[headers[key]])
          } else {
            return item[headers[key]]
          }
        })
        return res
      })
      return { headerData, bodyData }
    },
    // 编辑角色
    async  editRole(id) {
      this.userId = id // props传值 是异步的
      await this.$refs.assignRole.getUserDetailById(id) // 父组件调用子组件方法
      this.showRoleDialog = true
    }
  }
}
</script>

<style lang="scss" scoped></style>
